module.exports = {
  chooseImg,//上传头像
  request,//请求封装函数
  uploadFile,//图片上传函数
  getMemberDetail,
  submitObjectPicture,
}


function doLoginOther(okWay, app) {
  //调用登录接口
  wx.login({
    success: function (r) {
      console.log(r)
      var code = r.code; //登录凭证
      if (code) {
        wx.getUserInfo({
          withCredentials: false,
          success: function (res) {
            if (res.userInfo != null) {
              var avatarUrl = res.userInfo.avatarUrl
              var url = app.serverUrl + 'api/getOpenidInfo.json';
              wx.request({
                url: url,
                dataType: 'json',
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                data: { "appid": app.appid, "secret": app.secret, "js_code": code, "type": 'lc' },
                success: function (data) {
                  doLogin(that.serverUrl, that.globalData.userInfo.nickName, that.publicNo, data.data, that.siteID, that.deviceID, avatarUrl)
                  var flag = false;
                  if (flag) {
                    return;
                  }
                  flag = true;
                  wx.showToast({
                    title: '登录中',
                    icon: 'loading',
                    duration: 10000
                  })
                  var ipAddress = '';
                  var recommandID = wx.getStorageSync('recommandID');
                  wx.request({
                    url: 'https://pv.sohu.com/cityjson?ie=utf-8',
                    dataType: 'json',
                    method: 'POST',
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    success: function (address) {
                      var reg = /\{(.*)\}/.exec(address.data)[0]
                      var obj = JSON.parse(reg);
                      wx.request({
                        url: app.serverUrl + 'api/appLogin.json',
                        dataType: 'json',
                        method: 'POST',
                        header: {
                          'content-type': 'application/x-www-form-urlencoded'
                        },
                        data: {
                          "name": res.userInfo.nickName,
                          "code": data.data,
                          "appServerCode": app.publicNo,
                          "siteID": app.siteID,
                          "deviceID": app.deviceID,
                          "loginType": 2,
                          "type": 2,
                          "reUrl": res.userInfo.avatarUrl,
                          "ipAddress": obj.cip,
                          "memberID": recommandID == null ? '' : recommandID
                        },
                        success: function (data) {
                          flag = false;
                          if (data.data.header.code == 0) {
                            wx.getLocation({
                              type: 'gcj02',
                              success: function (res) {
                                wx.setStorageSync("USER_MAPX", res.longitude);
                                wx.setStorageSync("USER_MAPY", res.latitude);
                                wx.request({
                                  url: app.serverUrl + 'api/getNowAddress.json',
                                  dataType: 'json',
                                  method: 'POST',
                                  header: {
                                    'content-type': 'application/x-www-form-urlencoded'
                                  },
                                  data: { "latitude": res.latitude, "longitude": res.longitude },
                                  success: function (data) {
                                    wx.request({
                                      url: app.serverUrl + 'api/submitMyMapLocation.json',
                                      dataType: 'json',
                                      method: 'POST',
                                      header: {
                                        'content-type': 'application/x-www-form-urlencoded'
                                      },
                                      data: {
                                        "sessionID": wx.getStorageSync('USER_SESSIONID'),
                                        "mapX": res.longitude,
                                        "mapY": res.latitude,
                                        "mapAddress": data.data.address
                                      },
                                      success: function (e) {
                                        console.log(e)
                                      }
                                    })
                                  }
                                })
                              },
                            })

                            wx.hideToast();
                            wx.setStorage({ key: "USER_OPENID", data: data.data.body.member.weixinToken })
                            wx.setStorage({ key: "USER_SESSIONID", data: data.data.body.sessionID })
                            wx.setStorage({ key: "USER_MEMBERID", data: data.data.body.memberID })
                            wx.setStorage({ key: "USER_MEMBER", data: data.data.body.member })
                            okWay(data);
                          } else {
                            wx.showToast({
                              title: data.data.body.msg,
                              icon: 'success',
                              duration: 2000
                            })
                            console.error(data.data.body.msg)
                          }
                        },
                        error: function () {
                          flag = false;
                          wx.showToast({
                            title: '登录失败，请联系管理员',
                            icon: 'success',
                            duration: 2000
                          })
                          wx.hideToast();
                        }
                      })
                    }
                  })
                }
              })
            }

          }
        });
      }
    }
  });
}

/**
 * [request 请求封装]
 * @param [Object] app app对象
 * @param [String] url api地址
 * @param [Object] data 请求参数
 * @param [Function] cb 请求成功回调函数 如有第二个参数则为出错
 * @returns void
 *
 */
function request(app, url, data, cb) {
  if (url.indexOf('https') === -1) url = `${app.serverUrl}api/${url}`
  wx.request({
    url,
    dataType: 'json',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data,
    success(res) {
      const code = res.data.header.code;
      if (code == 10000) {
        // 先登录
        doLoginOther((loginData) => {
          // 赋值新的sessionID
          data.sessionID = loginData.data.body.sessionID;
          // 登录完毕再次发送请求
          request(app, url, data, cb);
        }, app);
      } else if (code === 0) {
        // 请求成功回调
        if (cb) cb(res);
      } else {
        // 其他错误 true代表出错了
        if (cb) cb(res, true);
      }
    }
  })
}

//上传头像
function chooseImg(that, serverUrl, setImage) {
  wx.chooseImage({
    success: function (res) {
      var tempFilePaths = res.tempFilePaths;
      wx.showToast({
        title: '上传中..',
        icon: 'loading',
        duration: 20000
      })
      wx.uploadFile({
        url: serverUrl + 'api/files/local.json',
        filePath: tempFilePaths[0],
        name: "file",
        dataType: 'json',
        success: function (res) {
          var data = JSON.parse(res.data);
          var sessionID = wx.getStorageSync('USER_SESSIONID');

          saveAvatar(function (res) {
            if (res.header.code == 0) {
              wx.hideToast();
              var member = wx.getStorageSync('USER_MEMBER');
              member.avatarURL = data.body.url;
              setImage(data.body.url)
              wx.setStorageSync('USER_MEMBER', member);
            } else {
              wx.showToast({
                title: '上传失败',
                icon: 'loading',
                duration: 20000
              })
            }
          }, sessionID, data.body.url, serverUrl)

        },
        error: function () {
          wx.hideToast();
        }
      })
    }
  })
}

//保存图片到storage
function saveAvatar(okway, sessionID, avatarUrl, serverUrl) {
  wx.request({
    url: serverUrl + 'api/saveAvatar.json',
    dataType: 'json',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: {
      "sessionID": sessionID,
      "avatarUrl": avatarUrl
    },
    success: function (res) {
      wx.hideToast();
      if (res.data.header.code == 0) {
        okway(res.data);
      } else {
        if (res.data.header.code == 10000) {
          doLoginOther(function (data) {
            if (data.data.header.code == 0) {
              sessionID = data.data.body.sessionID;
              saveAvatar(sessionID, avatarUrl, serverUrl)
            }
          }, app)
        } else {
          wx.showToast({
            title: res.data.header.msg == null ? '修改失败' : res.data.header.msg,
            icon: 'loading',
            duration: 2000
          })
        }
      }
    }
  })
}
/**
 * [request 图片上传]
 * @param null
 * @returns void
 */
function chooseimage() {
  var that = this;
  wx.chooseImage({
    success: function (res) {
      var tempFilePaths = res.tempFilePaths;
      var serverUrl = app.serverUrl;
      for (var index in tempFilePaths) {
        uploadFile(that, serverUrl, tempFilePaths[index]);
      }
    }
  })
}

/**
 * [request 图片上传]
 * @param [string] serverUrl url地址
 * @param [Object] filePath 图片
 * @returns void
 *
 */
function uploadFile(that, serverUrl, filePath) {
  wx.uploadFile({
    url: serverUrl + 'api/files/local.json',
    filePath: filePath,
    name: 'file',
    dataType: 'json',
    success: function (res) {
      var data = JSON.parse(res.data);
      var image = that.data.image;
      var imageUrl = [];
      imageUrl.push(data);
      for (var i = 0; i < imageUrl.length; i++) {
        image.push(imageUrl[i].body.url)
      }
      image = Array.from(new Set(that.data.image));
      if (image.length == 9) {
        that.setData({
          isSixImg: false
        });
      }
      else if (image.length > 9) {
        that.setData({
          isSixImg: false
        });
        image.splice(9);
        image = Array.from(new Set(image));
        wx.showToast({
          title: '最多只能上传6张图片',
          icon: 'none',
          duration: 700
        });
      }
      else {
        wx.showToast({
          title: '图片上传成功',
          icon: 'success',
          duration: 1500
        });
      }
      that.setData({
        image: image
      });
    },
    fail: function (res) {
      var res = res.errMsg
      wx.showToast({
        title: res,
        duration: 1500
      });
    }
  })
}

// 获取个人详情
function getMemberDetail(that,app) {
  request(app, 'getMemberDetail.json', {
    sessionID: wx.getStorageSync('USER_SESSIONID')
  }, (res) => {
    let member = res.data.body.data.rows[0];
    that.setData({
      memDetail: res.data.body.data.rows[0],
      member: member,
      avatar: member.avatarURL
    })
  });
}

//上传附件图
function submitObjectPicture(app, sessionID, objectDefineID, objectID, objectName, memberID, imageUrl, fileType, showType, name,cb) {
  request(app, 'submitObjectPicture.json', {
    sessionID: sessionID,
    objectDefineID: objectDefineID,
    objectID: objectID,
    objectName: objectName,
    memberID: memberID,
    imageUrl: imageUrl,
    fileType: fileType,
    showType: showType,
    name: name
  }, (res) => {
    cb()
  });
}
//删除附件图
function removeObjectPicture(that, attachmentID){
    request(app, 'removeObjectPicture.json', {
    sessionID: wx.getStorageSync('USER_SESSIONID'),
    attachmentID: attachmentID
  }, (res) => {
  })
}
//会员详细信息
function getMemberDetailTwo(app,that) {
  request(app, 'getMemberDetail.json', {
    sessionID: wx.getStorageSync('USER_SESSIONID'),
  }, (res) => {
    console.log(res)
    if (res.data.header.code == 0) {
      that.setData({
        member: res.data.body.data.rows[0]
      })
    }
  })
}

/**
 * @Author: pikaz
 * @Date:   2018-05-03T18:39:09+08:00
 * @Last modified by:   pikaz
 * @Last modified time: 2018-05-04T09:38:02+08:00
 */

module.exports = {
  chooseImg,//上传头像
  request,//请求封装函数
  uploadFile,//图片上传函数
  getMemberDetail,
  submitObjectPicture,
  doLoginOther
}

var flag = false;

var loginFlag = false

function login(result, app, name, openid, avatarUrl) {
  if (loginFlag) {
    return
  }
  var recommandID = wx.getStorageSync('recommandID');
  wx.request({
    url: app.serverUrl + 'api/appLogin.json',
    dataType: 'json',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: {
      "name": name,
      "code": openid,
      "appServerCode": app.publicNo,
      "siteID": app.siteID,
      "deviceID": app.deviceID,
      "loginType": 2,
      "type": 2,
      "reUrl": avatarUrl,
      "ipAddress": app.ipAddress,
      "memberID": recommandID == null ? '' : recommandID
    },
    success: function (data) {
      loginFlag = false
      if (data.data.header.code == 0) {
        flag = false
        wx.hideToast();
        //console.info(data.data.body)
        wx.setStorage({
          key: "USER_OPENID",
          data: openid
        })
        wx.setStorage({
          key: "USER_SESSIONID",
          data: data.data.body.sessionID
        })
        wx.setStorage({
          key: "USER_MEMBERID",
          data: data.data.body.memberID
        })
        wx.setStorage({
          key: "USER_MEMBER",
          data: data.data.body.member
        })
        result(data)
      } else {
        wx.showToast({
          title: data.data.body.msg,
          icon: 'success',
          duration: 2000
        })
       // console.error(data.data.body.msg)
      }
    },
    error: function () {
      loginFlag = false
      wx.showToast({
        title: '登录失败，请联系管理员',
        icon: 'success',
        duration: 2000
      })
      wx.hideToast();
    }
  })
}
